<template>
	<view class="form-container">
		<!-- 表单内容 -->
		<view class="form-content">
			<view class="form-item">
				<text class="form-label">计划号</text>
				<input 
					class="form-input" 
					v-model="formData.planNumber" 
					placeholder="请输入计划号"
					:disabled="isViewMode"
				/>
			</view>
			
			<view class="form-item">
				<text class="form-label">车牌号 <text class="required">*</text></text>
				<view 
					class="picker-input" 
					@click="selectCar"
					:class="{ 'disabled': isViewMode }"
				>
					<text class="picker-text" :class="{ 'placeholder': !formData.licensePlate }">
						{{ formData.licensePlate || '请选择车辆' }}
					</text>
					<text class="picker-arrow">></text>
				</view>
			</view>
			
			<view class="form-item">
				<text class="form-label">驾驶员</text>
				<input 
					class="form-input" 
					v-model="formData.driver" 
					placeholder="驾驶员信息（自动填充）"
					:disabled="true"
				/>
			</view>
			
			<view class="form-item">
				<text class="form-label">销售物料</text>
				<input 
					class="form-input" 
					v-model="formData.material" 
					placeholder="请输入销售物料"
					:disabled="isViewMode"
				/>
			</view>
			
			<view class="form-item">
				<text class="form-label">打印时间</text>
				<picker 
					mode="multiSelector" 
					:value="printTimeIndex" 
					:range="printTimeRange"
					@change="onPrintTimeChange"
					:disabled="isViewMode"
				>
					<view class="picker-input">
						<text class="picker-text" :class="{ 'placeholder': !formData.printTime }">
							{{ formData.printTime || '请选择打印时间' }}
						</text>
						<text class="picker-arrow">></text>
					</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="form-label">二磅时间</text>
				<picker 
					mode="multiSelector" 
					:value="weighTimeIndex" 
					:range="weighTimeRange"
					@change="onWeighTimeChange"
					:disabled="isViewMode"
				>
					<view class="picker-input">
						<text class="picker-text" :class="{ 'placeholder': !formData.weighTime }">
							{{ formData.weighTime || '请选择二磅时间' }}
						</text>
						<text class="picker-arrow">></text>
					</view>
				</picker>
			</view>
			
			<!-- 图片上传区域 -->
			<view class="form-item">
				<text class="form-label">质检单图片</text>
				<view class="upload-container">
					<!-- 已上传的图片列表 -->
					<view class="image-list">
						<view 
							v-for="(image, index) in uploadedImages" 
							:key="index" 
							class="image-item"
						>
							<image 
								:src="image.url" 
								class="uploaded-image"
								mode="aspectFill"
								@click="previewImage(image.url, index)"
							/>
							<view 
								class="delete-btn" 
								@click="deleteImage(index)"
								v-if="!isViewMode"
							>
								<text class="delete-icon">×</text>
							</view>
						</view>
						
						<!-- 添加图片按钮 -->
						<view 
							class="add-image-btn" 
							@click="chooseImage"
							v-if="!isViewMode && uploadedImages.length < maxImageCount"
						>
							<text class="add-icon">+</text>
							<text class="add-text">添加图片</text>
						</view>
					</view>
					
					<!-- 上传提示 -->
					<view class="upload-tips">
						<text class="tips-text">最多上传{{ maxImageCount }}张图片，支持JPG、PNG格式</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 隐藏的canvas用于生成质检单 -->
		<canvas 
			canvas-id="quality-canvas" 
			id="quality-canvas"
			style="position: fixed; top: -9999rpx; left: -9999rpx; width: 500px; height: 800px;"
		></canvas>
		
		<!-- 质检单预览弹窗 -->
		<u-popup 
			v-model="showQualityModal" 
			mode="bottom" 
			:border-radius="20"
			:closeable="true"
			@close="closeQualityModal"
		>
			<view class="quality-popup">
				<view class="popup-header">
					<text class="popup-title">质检单预览</text>
				</view>
				<view class="popup-body">
					<image 
						:src="qualityImageUrl" 
						class="preview-image"
						mode="aspectFit"
						@click="previewQualityImage"
						v-if="qualityImageUrl"
					/>
					<view class="preview-placeholder" v-else>
						<text class="placeholder-text">质检单预览</text>
					</view>
				</view>
				<view class="popup-footer">
					<button class="btn btn-cancel" @click="saveQrcodeToAlbum">保存二维码</button>
					<button class="btn btn-save" @click="saveQualityToAlbum">保存质检单</button>
				</view>
			</view>
		</u-popup>
		
		<!-- 操作按钮 -->
		<view class="action-buttons" v-if="!isViewMode">
			<button class="btn btn-cancel" @click="handleCancel">取消</button>
			<button class="btn btn-qrcode" @click="getQrcode">保存二维码</button>
			<button class="btn btn-submit" @click="handleSubmit">保存</button>
		</view>
		
		<view class="action-buttons" v-else>
			<button class="btn btn-edit" @click="handleEdit">编辑</button>
			<button class="btn btn-qrcode" @click="getQrcode">保存二维码</button>
			<button class="btn btn-delete" @click="handleDelete">删除</button>
		</view>
	</view>
</template>

<script>
	import api from '../../config/api.js'
	
	export default {
		data() {
			return {
				isViewMode: false, // 是否为查看模式
				currentId: null, // 当前质检单ID
				formData: {
					planNumber: '',
					licensePlate: '',
					driver: '',
					driverName: '',
					driverPhone: '',
					material: '',
					printTime: '',
					weighTime: ''
				},
				printTimeIndex: [0, 0, 0],
				weighTimeIndex: [0, 0, 0],
				printTimeRange: [[], [], []],
				weighTimeRange: [[], [], []],
				uploadedImages: [], // 已上传的图片列表
				maxImageCount: 9, // 最大上传图片数量
				uploading: false, // 是否正在上传
				showQualityModal: false, // 是否显示质检单预览弹窗
				qrcodeImageUrl: '', // 二维码图片地址
				qualityImageUrl: '' // 质检单图片地址
			}
		},
		
		onLoad(options) {
			// 初始化时间选择器数据
			this.initTimePicker();
			
			// 如果有ID参数，说明是查看/编辑模式
			if (options.id) {
				this.currentId = options.id;
				this.isViewMode = true;
				this.loadData(options.id);
			}
			
			// 监听车辆选择事件
			uni.$on('selectCar', this.onCarSelected);
		},
		
		onUnload() {
			// 页面卸载时移除事件监听
			uni.$off('selectCar', this.onCarSelected);
		},
		
		methods: {
			// 初始化时间选择器
			initTimePicker() {
				const currentDate = new Date();
				const years = [];
				const months = [];
				const days = [];
				const hours = [];
				const minutes = [];
				const seconds = [];
				
				// 生成年份（当前年份前后5年）
				for (let i = currentDate.getFullYear() - 5; i <= currentDate.getFullYear() + 5; i++) {
					years.push(i + '年');
				}
				
				// 生成月份
				for (let i = 1; i <= 12; i++) {
					months.push(i + '月');
				}
				
				// 生成日期
				for (let i = 1; i <= 31; i++) {
					days.push(i + '日');
				}
				
				// 生成小时
				for (let i = 0; i < 24; i++) {
					hours.push(i.toString().padStart(2, '0') + '时');
				}
				
				// 生成分钟
				for (let i = 0; i < 60; i++) {
					minutes.push(i.toString().padStart(2, '0') + '分');
				}
				
				// 生成秒
				for (let i = 0; i < 60; i++) {
					seconds.push(i.toString().padStart(2, '0') + '秒');
				}
				
				this.printTimeRange = [years, months, days, hours, minutes, seconds];
				this.weighTimeRange = [years, months, days, hours, minutes, seconds];
			},
			
			// 打印时间选择变化
			onPrintTimeChange(e) {
				this.printTimeIndex = e.detail.value;
				const timeRange = this.printTimeRange;
				const selectedTime = `${timeRange[0][e.detail.value[0]].replace('年', '')}-${timeRange[1][e.detail.value[1]].replace('月', '').padStart(2, '0')}-${timeRange[2][e.detail.value[2]].replace('日', '').padStart(2, '0')} ${timeRange[3][e.detail.value[3]].replace('时', '').padStart(2, '0')}:${timeRange[4][e.detail.value[4]].replace('分', '').padStart(2, '0')}:${timeRange[5][e.detail.value[5]].replace('秒', '').padStart(2, '0')}`;
				this.formData.printTime = selectedTime;
			},
			
			// 二磅时间选择变化
			onWeighTimeChange(e) {
				this.weighTimeIndex = e.detail.value;
				const timeRange = this.weighTimeRange;
				const selectedTime = `${timeRange[0][e.detail.value[0]].replace('年', '')}-${timeRange[1][e.detail.value[1]].replace('月', '').padStart(2, '0')}-${timeRange[2][e.detail.value[2]].replace('日', '').padStart(2, '0')} ${timeRange[3][e.detail.value[3]].replace('时', '').padStart(2, '0')}:${timeRange[4][e.detail.value[4]].replace('分', '').padStart(2, '0')}:${timeRange[5][e.detail.value[5]].replace('秒', '').padStart(2, '0')}`;
				this.formData.weighTime = selectedTime;
			},
			
			// 设置时间选择器的值
			setTimePickerValue(timeString, type) {
				if (!timeString) return;
				
				try {
					const date = new Date(timeString);
					const year = date.getFullYear();
					const month = date.getMonth() + 1;
					const day = date.getDate();
					const hour = date.getHours();
					const minute = date.getMinutes();
					const second = date.getSeconds();
					
					// 计算在数组中的索引
					const yearIndex = Math.max(0, year - (new Date().getFullYear() - 5));
					const monthIndex = month - 1;
					const dayIndex = day - 1;
					const hourIndex = hour;
					const minuteIndex = minute;
					const secondIndex = second;
					
					if (type === 'print') {
						this.printTimeIndex = [yearIndex, monthIndex, dayIndex, hourIndex, minuteIndex, secondIndex];
					} else if (type === 'weigh') {
						this.weighTimeIndex = [yearIndex, monthIndex, dayIndex, hourIndex, minuteIndex, secondIndex];
					}
				} catch (error) {
					console.error('设置时间选择器值失败:', error);
				}
			},
			
			// 加载数据
			async loadData(id) {
				if (!id) return;
				
				uni.showLoading({
					title: '加载中...'
				});
				
				try {
					const res = await this.$api.qualityInspection.read(id);
					console.log('质检单详情:', res);
					
					if (res && res.id) {
						// 保存当前ID
						this.currentId = res.id;
						
						// 填充表单数据（使用下划线字段名）
						this.formData = {
							planNumber: res.plan_number || '',
							licensePlate: res.license_plate || '',
							driver: res.driver || '',
							driverName: res.driver_name || '',
							driverPhone: res.driver_phone || '',
							material: res.material || '',
							printTime: res.print_time || '',
							weighTime: res.weigh_time || ''
						};
						
						// 设置时间选择器的值
						if (res.print_time) {
							this.setTimePickerValue(res.print_time, 'print');
						}
						if (res.weigh_time) {
							this.setTimePickerValue(res.weigh_time, 'weigh');
						}
						
						// 设置已上传的图片
						if (res.images) {
							this.uploadedImages = res.images.split(',').map(img => ({
								url: img,
								id: img
							}));
						} else {
							this.uploadedImages = [];
						}
					} else {
						uni.showToast({
							title: '数据不存在',
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				} catch (error) {
					console.log('加载质检单详情失败:', error);
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} finally {
					uni.hideLoading();
				}
			},
			
			// 取消操作
			handleCancel() {
				uni.navigateBack();
			},
			
			// 保存数据
			async handleSubmit() {
				// 表单验证
				if (!this.formData.planNumber) {
					uni.showToast({
						title: '请输入计划号',
						icon: 'none'
					});
					return;
				}
				
				if (!this.formData.licensePlate) {
					uni.showToast({
						title: '请选择车辆',
						icon: 'none'
					});
					return;
				}
				
				if (!this.formData.material) {
					uni.showToast({
						title: '请输入销售物料',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({
					title: '保存中...'
				});
				
				try {
					// 准备提交的数据（转换为下划线格式）
					const submitData = {
						plan_number: this.formData.planNumber,
						license_plate: this.formData.licensePlate,
						driver: this.formData.driver,
						driver_name: this.formData.driverName,
						driver_phone: this.formData.driverPhone,
						material: this.formData.material,
						print_time: this.formData.printTime,
						weigh_time: this.formData.weighTime,
						images: this.uploadedImages.map(img => img.url).join(',')
					};
					
					let res;
					if (this.currentId) {
						// 更新现有质检单
						res = await this.$api.qualityInspection.update(this.currentId, submitData);
					} else {
						// 创建新质检单
						res = await this.$api.qualityInspection.create(submitData);
					}
					
					console.log('保存结果:', res);
					
					uni.hideLoading();
					uni.showToast({
						title: this.currentId ? '更新成功' : '创建成功',
						icon: 'success'
					});
					
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
					
				} catch (error) {
					console.error('保存失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '保存失败，请重试',
						icon: 'none'
					});
				}
			},
			
			// 编辑模式
			handleEdit() {
				this.isViewMode = false;
			},
			
			// 删除质检单
			async handleDelete() {
				if (!this.currentId) {
					uni.showToast({
						title: '无法删除',
						icon: 'none'
					});
					return;
				}
				
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个质检单吗？删除后无法恢复。',
					confirmText: '删除',
					confirmColor: '#FF3B30',
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '删除中...'
							});
							
							try {
								await this.$api.qualityInspection.delete(this.currentId);
								
								uni.hideLoading();
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
								
								setTimeout(() => {
									uni.navigateBack();
								}, 1500);
								
							} catch (error) {
								console.error('删除失败:', error);
								uni.hideLoading();
								uni.showToast({
									title: '删除失败，请重试',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 返回
			handleBack() {
				uni.navigateBack();
			},
			
			// 选择图片
			chooseImage() {
				if (this.uploading) {
					uni.showToast({
						title: '正在上传中，请稍候',
						icon: 'none'
					});
					return;
				}
				
				const remainingCount = this.maxImageCount - this.uploadedImages.length;
				uni.chooseImage({
					count: remainingCount,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.uploadImages(res.tempFilePaths);
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 上传图片
			async uploadImages(filePaths) {
				this.uploading = true;
				uni.showLoading({
					title: '上传中...'
				});
				
				try {
					const uploadPromises = filePaths.map(filePath => this.uploadSingleImage(filePath));
					const results = await Promise.all(uploadPromises);
					
					// 过滤掉上传失败的图片
					const successResults = results.filter(result => result.success);
					
					// 添加到已上传图片列表
					this.uploadedImages.push(...successResults.map(result => ({
						url: result.data.url,
						id: result.data.id || Date.now().toString()
					})));
					
					uni.hideLoading();
					uni.showToast({
						title: `成功上传${successResults.length}张图片`,
						icon: 'success'
					});
					
				} catch (error) {
					console.error('批量上传失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '上传失败，请重试',
						icon: 'none'
					});
				} finally {
					this.uploading = false;
				}
			},
			
			// 上传单张图片
			uploadSingleImage(filePath) {
				return new Promise((resolve) => {
					uni.uploadFile({
						url: api.uploadImage,
						filePath: filePath,
						name: 'file',
						header: {
							'Authorization': uni.getStorageSync('token') || ''
						},
						success: (res) => {
							try {
								const data = JSON.parse(res.data);
								if (data.code === 200) {
									resolve({
										success: true,
										data: data.data
									});
								} else {
									resolve({
										success: false,
										error: data.msg || '上传失败'
									});
								}
							} catch (e) {
								resolve({
									success: false,
									error: '响应解析失败'
								});
							}
						},
						fail: (error) => {
							resolve({
								success: false,
								error: error.errMsg || '上传失败'
							});
						}
					});
				});
			},
			
			// 预览图片
			previewImage(current, index) {
				const urls = this.uploadedImages.map(img => img.url);
				uni.previewImage({
					current: current,
					urls: urls
				});
			},
			
			// 删除图片
			deleteImage(index) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这张图片吗？',
					confirmText: '删除',
					confirmColor: '#FF3B30',
					success: (res) => {
						if (res.confirm) {
							this.uploadedImages.splice(index, 1);
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						}
					}
				});
			},
			
			// 选择车辆
			selectCar() {
				if (this.isViewMode) {
					return;
				}
				
				uni.navigateTo({
					url: '/pages/car/car?selectMode=true'
				});
			},
			
			// 车辆选择回调
			onCarSelected(car) {
				// 处理车辆数据，支持驼峰和下划线两种格式
				this.formData.licensePlate = car.license_plate || car.licensePlate;
				this.formData.driverName = car.driver_name || car.driverName;
				this.formData.driverPhone = car.driver_phone || car.driverPhone;
				this.formData.driver = `${this.formData.driverPhone}-${this.formData.driverName}`;
				
				uni.showToast({
					title: '车辆选择成功',
					icon: 'success'
				});
			},
			
			// 生成质检单
			async getQrcode() {
				try {
					// 检查是否有质检单ID
					if (!this.currentId) {
						uni.showToast({
							title: '请先保存质检单',
							icon: 'none'
						});
						return;
					}
					
					uni.showLoading({
						title: '生成质检单中...'
					});
					
					// 先获取二维码图片
					await this.fetchQrcodeImage();
					uni.showLoading({
						title: '生成质检单中...'
					});
					
					// 绘制质检单
					await this.drawQualitySlip();
					
					uni.hideLoading();
					// 显示预览弹窗
					this.showQualityModal = true;
					
				} catch (error) {
					console.error('生成质检单出错:', error);
					uni.hideLoading();
					uni.showToast({
						title: '生成失败，请重试',
						icon: 'none'
					});
				}
			},
			
			// 获取二维码图片
			async fetchQrcodeImage() {
				try {
					const res = await this.$api.qualityInspection.getQrcode(this.currentId);
					if (res) {
						this.qrcodeImageUrl = res;
					} else {
						throw new Error('获取二维码失败');
					}
				} catch (error) {
					console.error('获取二维码图片失败:', error);
					// 如果接口失败，使用默认的二维码图片或生成一个
					this.qrcodeImageUrl = '';
					throw error;
				}
			},
			
			// 绘制质检单
			async drawQualitySlip() {
				return new Promise((resolve, reject) => {
					const canvasId = 'quality-canvas';
					const ctx = uni.createCanvasContext(canvasId, this);
					
					// 设置画布尺寸
					const canvasWidth = 500;
					const canvasHeight = 800;
					
					// 绘制白色背景
					ctx.setFillStyle('#FFFFFF');
					ctx.fillRect(0, 0, canvasWidth, canvasHeight);
					
					// 设置字体样式
					ctx.setFontSize(32);
					ctx.setFillStyle('#333333');
					
					// 绘制标题
					ctx.setTextAlign('center');
					ctx.fillText('质检单信息', canvasWidth / 2, 80);
					
					// 绘制信息内容
					ctx.setTextAlign('left');
					ctx.setFontSize(24);
					
					let yPos = 150;
					const lineHeight = 50;
					
					// 计划号
					ctx.fillText('计划号:', 85, yPos);
					ctx.fillText(this.formData.planNumber || '', 170, yPos);
					yPos += lineHeight;
					
					// 车牌号
					ctx.fillText('车牌号:', 85, yPos);
					ctx.fillText(this.formData.licensePlate || '', 170, yPos);
					yPos += lineHeight;
					
					// 驾驶员
					ctx.fillText('驾驶员:', 85, yPos);
					ctx.fillText(this.formData.driver || '', 170, yPos);
					yPos += lineHeight;
					
					// 销售物料
					ctx.fillText('销售物料:', 60, yPos);
					ctx.fillText(this.formData.material || '', 170, yPos);
					yPos += lineHeight;
					
					// 打印时间
					ctx.fillText('打印时间:', 60, yPos);
					ctx.fillText(this.formData.printTime || '', 170, yPos);
					yPos += lineHeight + 20;
					
					// 绘制二维码提示文字
					ctx.setFontSize(24);
					ctx.setTextAlign('center');
					ctx.fillText('扫描下方二维码查看质检信息:', canvasWidth / 2, yPos);
					yPos += 40;
					
					// 绘制二维码区域
					const qrSize = 200;
					const qrX = (canvasWidth - qrSize) / 2;
					const qrY = yPos;
					
					console.log(this.qrcodeImageUrl, 'qrcodeImageUrl');
					
					// 如果有二维码图片，先预加载图片再绘制
					if (this.qrcodeImageUrl) {
						this.drawQrcodeImage(ctx, qrX, qrY, qrSize, () => {
							// 完成绘制
							ctx.draw(false, () => {
								// 将canvas转换为图片
								this.convertCanvasToImage();
								resolve();
							});
						});
					} else {
						// 完成绘制
						ctx.draw(false, () => {
							// 将canvas转换为图片
							this.convertCanvasToImage();
							resolve();
						});
					}
				});
			},
			
			// 绘制二维码图片（等待图片加载完成）
			drawQrcodeImage(ctx, qrX, qrY, qrSize, callback) {
				// 使用小程序的图片预加载API
				uni.getImageInfo({
					src: this.qrcodeImageUrl,
					success: (res) => {
						console.log('二维码图片加载成功:', res);
						// 图片加载完成后绘制
						ctx.drawImage(res.path, qrX + 4, qrY + 4, qrSize - 8, qrSize - 8);
						callback();
					},
					fail: (err) => {
						console.error('二维码图片加载失败:', err);
						callback();
					}
				});
			},
			
			// 将canvas转换为图片
			convertCanvasToImage() {
				// 获取主canvas的图片数据
				uni.canvasToTempFilePath({
					canvasId: 'quality-canvas',
					success: (res) => {
						// 设置质检单图片URL用于弹窗显示
						this.qualityImageUrl = res.tempFilePath;
					},
					fail: (err) => {
						console.error('转换canvas为图片失败:', err);
						uni.showToast({
							title: '生成预览失败',
							icon: 'none'
						});
					}
				}, this);
			},
			
			// 预览质检单图片
			previewQualityImage() {
				uni.previewImage({
					urls: [this.qualityImageUrl]
				})
			},
			
			// 关闭质检单预览弹窗
			closeQualityModal() {
				this.showQualityModal = false;
			},
			
			// 保存二维码到相册
			saveQrcodeToAlbum() {
				if (!this.qrcodeImageUrl) {
					uni.showToast({
						title: '二维码图片不存在',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({
					title: '保存中...'
				});
				
				// 先下载二维码图片到本地
				uni.downloadFile({
					url: this.qrcodeImageUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							// 保存到相册
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: () => {
									uni.hideLoading();
									uni.showToast({
										title: '二维码已保存到相册',
										icon: 'success'
									});
								},
								fail: (err) => {
									console.error('保存失败:', err);
									uni.hideLoading();
									uni.showToast({
										title: '保存失败，请检查权限',
										icon: 'none'
									});
								}
							});
						} else {
							uni.hideLoading();
							uni.showToast({
								title: '下载二维码失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('下载二维码失败:', err);
						uni.hideLoading();
						uni.showToast({
							title: '下载二维码失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 保存质检单到相册
			saveQualityToAlbum() {
				uni.showLoading({
					title: '保存中...'
				});
				
				uni.canvasToTempFilePath({
					canvasId: 'quality-canvas',
					success: (res) => {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.hideLoading();
								uni.showToast({
									title: '质检单已保存到相册',
									icon: 'success'
								});
								this.closeQualityModal();
							},
							fail: (err) => {
								console.error('保存失败:', err);
								uni.hideLoading();
								uni.showToast({
									title: '保存失败，请检查权限',
									icon: 'none'
								});
							}
						});
					},
					fail: (err) => {
						console.error('生成图片失败:', err);
						uni.hideLoading();
						uni.showToast({
							title: '生成图片失败',
							icon: 'none'
						});
					}
				}, this);
			}
		}
	}
</script>

<style scoped>
.form-container {
	min-height: 100vh;
	background-color: #F5F5F5;
	padding-bottom: 160rpx;
}

.page-header {
	background-color: #007AFF;
	padding: 30rpx;
	text-align: center;
}

.page-title {
	color: white;
	font-size: 36rpx;
	font-weight: bold;
}

.form-content {
	padding: 30rpx;
}

.form-item {
	background-color: white;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.form-label {
	display: block;
	color: #333;
	font-size: 28rpx;
	font-weight: 500;
	margin-bottom: 20rpx;
}

.required {
	color: #FF4D4F;
}

.form-input {
	width: 100%;
	height: 80rpx;
	border: 2rpx solid #E5E5E5;
	border-radius: 8rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	color: #333;
	background-color: #FAFAFA;
}

.form-input:focus {
	border-color: #007AFF;
	background-color: white;
}

.picker-input {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 80rpx;
	border: 2rpx solid #E5E5E5;
	border-radius: 8rpx;
	padding: 0 20rpx;
	background-color: #FAFAFA;
}

.picker-text {
	font-size: 28rpx;
	color: #333;
}

.picker-text.placeholder {
	color: #999;
}

.picker-arrow {
	font-size: 24rpx;
	color: #999;
}

.picker-input.disabled {
	background-color: #F5F5F5;
	opacity: 0.6;
}

.action-buttons {
	display: flex;
	padding: 30rpx;
	gap: 20rpx;
	background-color: white;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.btn {
	flex: 1;
	height: 80rpx;
	border-radius: 8rpx;
	font-size: 30rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
}

.btn-cancel {
	background-color: #F5F5F5;
	color: #666;
}

.btn-submit {
	background-color: #007AFF;
	color: white;
}

.btn-edit {
	background-color: #FF9500;
	color: white;
}

.btn-back {
	background-color: #F5F5F5;
	color: #666;
}

.btn-delete {
	background-color: #FF3B30;
	color: white;
}

.btn-qrcode {
	background-color: #34C759;
	color: white;
}

.btn:active {
	opacity: 0.8;
}

/* 图片上传样式 */
.upload-container {
	margin-top: 10rpx;
}

.image-list {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.image-item {
	position: relative;
	width: 200rpx;
	height: 200rpx;
	border-radius: 12rpx;
	overflow: hidden;
}

.uploaded-image {
	width: 100%;
	height: 100%;
	border-radius: 12rpx;
}

.delete-btn {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	width: 40rpx;
	height: 40rpx;
	background-color: #FF3B30;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2rpx 8rpx rgba(255, 59, 48, 0.3);
}

.delete-icon {
	color: white;
	font-size: 24rpx;
	font-weight: bold;
}

.add-image-btn {
	width: 200rpx;
	height: 200rpx;
	border: 2rpx dashed #CCCCCC;
	border-radius: 12rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #FAFAFA;
}

.add-image-btn:active {
	background-color: #F0F0F0;
}

.add-icon {
	font-size: 48rpx;
	color: #999;
	margin-bottom: 10rpx;
}

.add-text {
	font-size: 24rpx;
	color: #999;
}

.upload-tips {
	margin-top: 10rpx;
}

.tips-text {
	font-size: 24rpx;
	color: #999;
	line-height: 1.4;
}

/* 质检单预览弹窗样式 */
.quality-popup {
	background-color: white;
	min-height: 500rpx;
}

.popup-header {
	padding: 30rpx;
	text-align: center;
	border-bottom: 1rpx solid #E5E5E5;
}

.popup-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.popup-body {
	padding: 40rpx 30rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	min-height: 300rpx;
}

.preview-image {
	width: 300rpx;
	border: 2rpx solid #E5E5E5;
}

.preview-placeholder {
	width: 300rpx;
	height: 400rpx;
	border: 2rpx dashed #E5E5E5;
	border-radius: 12rpx;
	background-color: #F8F8F8;
	display: flex;
	align-items: center;
	justify-content: center;
}

.placeholder-text {
	font-size: 28rpx;
	color: #999;
}

.popup-footer {
	display: flex;
	padding: 30rpx;
	gap: 20rpx;
	background-color: #F8F8F8;
	border-top: 1rpx solid #E5E5E5;
}

.popup-footer .btn {
	flex: 1;
	height: 80rpx;
	border-radius: 12rpx;
	font-size: 30rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: 500;
}

.popup-footer .btn-cancel {
	background-color: #E5E5E5;
	color: #666;
}

.popup-footer .btn-save {
	background-color: #007AFF;
	color: white;
}

.popup-footer .btn:active {
	opacity: 0.8;
	transform: scale(0.98);
}
</style>
